package pl.olsson.plugin.script;

import java.io.Writer;

/**
 *
 * @author nilols
 */
public class ProxyWriter extends Writer {

    private Writer defaultWriter;
    private Writer currentWriter;

    public ProxyWriter(Writer writer) {
        defaultWriter = writer;
    }

    public void setWriter(Writer writer) {
        if (null != currentWriter) {
            try {
                currentWriter.flush();
                currentWriter.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        currentWriter = writer;
    }

    protected Writer getWriter() {
        return null!=currentWriter?currentWriter:defaultWriter;
    }

    @Override
    public void write(char[] chars, int i, int i1) {
        try {
            getWriter().write(chars, i, i1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void flush() {
        try {
            getWriter().flush();
        } catch (Exception e) {
                throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        if (null != currentWriter) {
            try {
                currentWriter.close();
                currentWriter = null;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
